import React, { useImperativeHandle, forwardRef, useState, useRef, memo, useCallback, useEffect } from 'react';
import { CameraRoll } from "@react-native-camera-roll/camera-roll";
import ImageView from "react-native-image-viewing";

const ImageViewing = (index) => {
    const [visible, setVisible] = useState(false)
    const [images, setImages] = useState([])
    const [imageIndex, setiImageIndex] = useState(index)

    const saveImageToPhone = async (uri, imageName) => {
        try {
            if (!uri) return null;
            return new Promise((resolve, reject) => {
                let timestamp = new Date().getTime(); //获取当前时间错
                let random = String((Math.random() * 1000000) | 0); //六位随机数
                let dirs =
                    Platform.OS === 'ios'
                        ? RNFS.LibraryDirectoryPath
                        : RNFS.ExternalDirectoryPath; //外部文件，共享目录的绝对路径（仅限android）
                const downloadDest = `${dirs}/${timestamp + random}.png`;
                const formUrl = uri;
                const options = {
                    fromUrl: formUrl,
                    toFile: downloadDest,
                    background: true,
                    begin: (res) => {
                        // console.log('begin', res);
                        // console.log('contentLength:', res.contentLength / 1024 / 1024, 'M');
                    },
                };
                try {
                    const ret = RNFS.downloadFile(options);
                    ret.promise
                        .then((res) => {
                            console.log(downloadDest)
                            // file:///data/user/0/com.tweet/cache/rn_image_picker_lib_temp_8f1ab6cf-4721-44d9-bb25-610797a8f1a6.jpg
                            // console.log('success', res);
                            // console.log('file://' + downloadDest)
                            var promise = CameraRoll.save(downloadDest);
                            promise
                                .then(function (result) {
                                    console.log(result)
                                    // alert('保存成功！地址如下：\n' + result);
                                })
                                .catch(function (error) {
                                    console.log('error', error);
                                    // alert('保存失败！\n' + error);
                                });
                            resolve(res);
                        })
                        .catch((err) => {
                            reject(new Error(err));
                        });
                } catch (e) {
                    reject(new Error(e));
                }
            });

        } catch (error) {
            console.error('保存图片时发生错误:', error);
        }
    }


    return <ImageView
        images={list}
        imageIndex={imageIndex}
        visible={visible}
        onLongPress={() => console.log("@22")}
        onRequestClose={() => setVisible(false)}
        FooterComponent={(data) => <Text style={[{ padding: 20, backgroundColor: "rgba(58, 192, 48, 1)" }]} onPress={() => saveImageToPhone('https://home.tweetwallet.io/upapi/inline/dH2uCGIRk2ru_dfyuhaDQXtO-xoCaNYhDsN3FvNO7nY.jpg', 'iadadadadmage.png')}>a水水水水水水水水水水水水水水水水水</Text>}
    />
}

export default ImageViewing